<template>
  <div class="home">
    <!-- 首页 -->
    <HomeHeader
      :category="category"
      @setCurrentCategory="setCurrentCategory"
    />
    <div
      class="home-container"
      ref="refreshElm"
    >
      <!-- 轮播图 -->
      <Suspense>
        <template #default>
          <HomeSwiper />
        </template>
        <template #fallback>
          <div>loading....</div>
        </template>
      </Suspense>
      <!-- 课程列表 -->
      <HomeList :lessonsList="lessonsList" />
      <div v-if="isLoading">loading....</div>
      <div v-if="!hasMore">暂无更多数据</div>
    </div>

  </div>
</template>

<script lang='ts'>
import { computed, defineComponent, onMounted, ref } from 'vue';
import HomeHeader from './home-header.vue';
import HomeSwiper from './home-swiper.vue';
import HomeList from './home-list.vue';
import { Store, useStore } from 'vuex';
import { IGlobalState } from '@/store';
import { CATEGORY_TYPES } from '@/typings/home';
import * as Types from '@/store/action-types';
import {useLoadMore } from '@/hooks/useLoadMore'
// 专门为修改分类所定义的函数
function useCategory(store: Store<IGlobalState>) {
  // 如果不用计算属性 就是一个死值
  let category = computed(() => {
    return store.state.home.CurrentCategory;
  });
  function setCurrentCategory(category: CATEGORY_TYPES) {
    store.commit(`home/${Types.SET_CATEGORY}`, category);
  }

  return {
    category,
    setCurrentCategory,
  };
}
function useLessensList(store: Store<IGlobalState>) {
  let lessonsList = computed(() => {
    return store.state.home.lessons.list;
  });
  onMounted(() => {
    console.log(lessonsList);
    // 初始化加载 如果vuex中有数据就不需要再加载数据
    if (lessonsList.value.length === 0) {
      store.dispatch(`home/${Types.SET_LESSON_LIST}`);
    }
  });
  return { lessonsList };
}
export default defineComponent({
  components: {
    HomeHeader,
    HomeSwiper,
    HomeList,
  },
  setup() {
    // 需要获取vux中的分类状态，还有个更改的功能
    let store = useStore<IGlobalState>();
    // 分类
    let { category, setCurrentCategory } = useCategory(store);
    // 课程列表
    let { lessonsList } = useLessensList(store);
    // 获取真实dom 如果是组件的话就是组件实例 名字要和上面的统一
    let refreshElm = ref<null | HTMLElement>(null);
    const {isLoading,hasMore} = useLoadMore(refreshElm,store,`home/${Types.SET_LESSON_LIST}`)
    return {
      category,
      setCurrentCategory,
      lessonsList,
      refreshElm,
      isLoading,
      hasMore
    };
  },
});
</script>

<style lang="scss" scoped>
.home {
  padding-top: 48px;
}
.home-container {
  position: absolute;
  top: 48px;
  bottom: 50px;
  width: 100%;
  overflow-y: scroll;
}
</style>
